The purpose of learning this course is that I would like to learn data analysis skill for the future career. Plus, this online course looks awesome!
Describe the work you have done this week and summarize your learning.
students2014 <- read.table(“http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/learning2014.txt”, sep=“,”, header=TRUE)
str(students2014)
The resource data is collected from the student self evaluation survey from course Introduction to Social Statistics, fall 2014 - in Finnish. This survey is devided into A, B, C and D parts. - Measures A and C are based on parts A and C in ASSIST (Approaches and Study Skills Inventory for Students). - Measures B (ASSIST B) are connected to the corresponding dimensions (Deep/SUrface/STrategic). - Measure D is based on SATS (Survey of Attitudes Toward Statistics). - Compared to the original 52 item ASSIST we here used a brief version (created by Primi, Chiesi et al), including 32 items.
The student2014 dataset has 7 variables, including gender, age, attitute, deep, str, surf, and points, and 166 rows. - gender: F (Female, 1), M (Male, 2) - age: age in years - attitude: Measure on the Likert scale (1-5) - deep: Measures B for deep questions - stra: Measures B for surface questions - surf: Measures B for strategic questions - points: Exam points excepted zero
ggpairs(learning2014, lower = list(combo = wrap(“facethist”, bins = 20)))
my_model2 <- lm(points ~ attitude + stra + surf, data = learning2014)
summary(my_model2)
According to the plot, we can see the correlation and distribution between each variables. For example, the top three variables relative data between points are attitude, stra and surf as 0.437, 0.146 and 0.144.
plot(my_model2, which = c(1,2,5), caption = list(“Residuals vs Fitted”, “Normal Q-Q”,“Residuals vs Leverage”))
my_model2 diagnostic plots
- Residuals vs Fitted: This plot shows if residuals have non-linear patterns. In the my_model2 diagnostic plots above, it shows the linear pattern in this data.
- Normal Q-Q: This plot shows if residuals are normally distributed. In the my_model2 diagnostic plots above, it shows the data is normally distributed.
- Residuals vs Leverage: This plot helps us to find influential cases.When cases are outside of the Cook’s distance (meaning they have high Cook’s distance scores), the cases are influential to the regression results. In the my_model2 diagnostic plots above, it seems no influential outliers.
alc <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/alc.txt", sep=",", header=TRUE)
str(alc)
## 'data.frame': 382 obs. of 35 variables:
## $ school : Factor w/ 2 levels "GP","MS": 1 1 1 1 1 1 1 1 1 1 ...
## $ sex : Factor w/ 2 levels "F","M": 1 1 1 1 1 2 2 1 2 2 ...
## $ age : int 18 17 15 15 16 16 16 17 15 15 ...
## $ address : Factor w/ 2 levels "R","U": 2 2 2 2 2 2 2 2 2 2 ...
## $ famsize : Factor w/ 2 levels "GT3","LE3": 1 1 2 1 1 2 2 1 2 1 ...
## $ Pstatus : Factor w/ 2 levels "A","T": 1 2 2 2 2 2 2 1 1 2 ...
## $ Medu : int 4 1 1 4 3 4 2 4 3 3 ...
## $ Fedu : int 4 1 1 2 3 3 2 4 2 4 ...
## $ Mjob : Factor w/ 5 levels "at_home","health",..: 1 1 1 2 3 4 3 3 4 3 ...
## $ Fjob : Factor w/ 5 levels "at_home","health",..: 5 3 3 4 3 3 3 5 3 3 ...
## $ reason : Factor w/ 4 levels "course","home",..: 1 1 3 2 2 4 2 2 2 2 ...
## $ nursery : Factor w/ 2 levels "no","yes": 2 1 2 2 2 2 2 2 2 2 ...
## $ internet : Factor w/ 2 levels "no","yes": 1 2 2 2 1 2 2 1 2 2 ...
## $ guardian : Factor w/ 3 levels "father","mother",..: 2 1 2 2 1 2 2 2 2 2 ...
## $ traveltime: int 2 1 1 1 1 1 1 2 1 1 ...
## $ studytime : int 2 2 2 3 2 2 2 2 2 2 ...
## $ failures : int 0 0 3 0 0 0 0 0 0 0 ...
## $ schoolsup : Factor w/ 2 levels "no","yes": 2 1 2 1 1 1 1 2 1 1 ...
## $ famsup : Factor w/ 2 levels "no","yes": 1 2 1 2 2 2 1 2 2 2 ...
## $ paid : Factor w/ 2 levels "no","yes": 1 1 2 2 2 2 1 1 2 2 ...
## $ activities: Factor w/ 2 levels "no","yes": 1 1 1 2 1 2 1 1 1 2 ...
## $ higher : Factor w/ 2 levels "no","yes": 2 2 2 2 2 2 2 2 2 2 ...
## $ romantic : Factor w/ 2 levels "no","yes": 1 1 1 2 1 1 1 1 1 1 ...
## $ famrel : int 4 5 4 3 4 5 4 4 4 5 ...
## $ freetime : int 3 3 3 2 3 4 4 1 2 5 ...
## $ goout : int 4 3 2 2 2 2 4 4 2 1 ...
## $ Dalc : int 1 1 2 1 1 1 1 1 1 1 ...
## $ Walc : int 1 1 3 1 2 2 1 1 1 1 ...
## $ health : int 3 3 3 5 5 5 3 1 1 5 ...
## $ absences : int 6 4 10 2 4 10 0 6 0 0 ...
## $ G1 : int 5 5 7 15 6 15 12 6 16 14 ...
## $ G2 : int 6 5 8 14 10 15 12 5 18 15 ...
## $ G3 : int 6 6 10 15 10 15 11 6 19 15 ...
## $ alc_use : num 1 1 2.5 1 1.5 1.5 1 1 1 1 ...
## $ high_use : logi FALSE FALSE TRUE FALSE FALSE FALSE ...
The dataset alc includes 35 varibles with 382 rows. The alc_use is the average of column Dalc and Walc (weekday and weekend alcohol consumption). If the average alcohol consumption is higher than 2, it is regarded as high alcohol usage student which is shown in column ‘high_use’ as TRUE.
Personally, I think alcohol consumption is related to a person’s relationship with family members, higher alcohol concumption may caused by bad relationship, so I select #24 famrel as one onf the analysis target. In addition, in my opinion, if a student tends to have a promising future, he/she may focus on study more rather than be absent in class too often, so I select #14 studytime and #30 absences as the interesing variables. Last, I am interested in if the score is related to alcohol consumption, so I choose #32 G3 as the fourth variable.
- #14 studytime - weekly study time (numeric: 1 - <2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - >10 hours)
- #24 famrel - quality of family relationships (numeric: from 1 - very bad to 5 - excellent)
- #30 absences - number of school absences (numeric: from 0 to 93)
- #32 G3 - final grade (numeric: from 0 to 20, output target)
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
alc_4 <- alc %>% select(16, 24, 30, 33, 34, 35)
head(alc_4, n=10)
## studytime famrel absences G3 alc_use high_use
## 1 2 4 6 6 1.0 FALSE
## 2 2 5 4 6 1.0 FALSE
## 3 2 4 10 10 2.5 TRUE
## 4 3 3 2 15 1.0 FALSE
## 5 2 4 4 10 1.5 FALSE
## 6 2 5 10 15 1.5 FALSE
## 7 2 4 0 11 1.0 FALSE
## 8 2 4 6 6 1.0 FALSE
## 9 2 4 0 19 1.0 FALSE
## 10 2 5 0 15 1.0 FALSE
high_use vs studytime
alc_4.v1 <- table(alc$high_use, alc$studytime)
round(prop.table(alc_4.v1,1), 2)
##
## 1 2 3 4
## FALSE 0.22 0.49 0.20 0.09
## TRUE 0.38 0.51 0.07 0.04
high_use vs famrel
alc_4.v2 <- table(alc$high_use, alc$famrel)
round(prop.table(alc_4.v2,1), 2)
##
## 1 2 3 4 5
## FALSE 0.03 0.03 0.15 0.49 0.31
## TRUE 0.02 0.08 0.23 0.46 0.21
high_use vs absences
alc_4.v3 <- table(alc$high_use, alc$absences)
round(prop.table(alc_4.v3,1), 2)
##
## 0 1 2 3 4 5 6 7 8 9 10 11 12 13
## FALSE 0.35 0.01 0.20 0.01 0.13 0.01 0.07 0.02 0.05 0.01 0.04 0.00 0.02 0.00
## TRUE 0.20 0.01 0.12 0.04 0.13 0.00 0.10 0.02 0.07 0.00 0.04 0.01 0.04 0.03
##
## 14 15 16 17 18 19 20 21 22 23 24 25 26 28
## FALSE 0.03 0.00 0.01 0.00 0.01 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
## TRUE 0.04 0.02 0.04 0.01 0.02 0.01 0.01 0.00 0.03 0.00 0.01 0.00 0.00 0.01
##
## 30 54 56 75
## FALSE 0.00 0.00 0.00 0.00
## TRUE 0.01 0.01 0.01 0.00
high_use vs G3
alc_4.v4 <- table(alc$high_use, alc$G3)
round(prop.table(alc_4.v4,1), 2)
##
## 0 4 5 6 7 8 9 10 11 12 13 14 15 16
## FALSE 0.12 0.00 0.01 0.05 0.02 0.06 0.07 0.13 0.11 0.07 0.05 0.09 0.10 0.05
## TRUE 0.05 0.01 0.04 0.02 0.02 0.14 0.08 0.20 0.11 0.10 0.11 0.03 0.04 0.04
##
## 17 18 19 20
## FALSE 0.01 0.04 0.02 0.00
## TRUE 0.02 0.02 0.00 0.00
## Loading required package: ggplot2
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
##
## Attaching package: 'GGally'
## The following object is masked from 'package:dplyr':
##
## nasa
library(dplyr)
library(MASS)
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
head(Boston, n=15)
## crim zn indus chas nox rm age dis rad tax ptratio black
## 1 0.00632 18.0 2.31 0 0.538 6.575 65.2 4.0900 1 296 15.3 396.90
## 2 0.02731 0.0 7.07 0 0.469 6.421 78.9 4.9671 2 242 17.8 396.90
## 3 0.02729 0.0 7.07 0 0.469 7.185 61.1 4.9671 2 242 17.8 392.83
## 4 0.03237 0.0 2.18 0 0.458 6.998 45.8 6.0622 3 222 18.7 394.63
## 5 0.06905 0.0 2.18 0 0.458 7.147 54.2 6.0622 3 222 18.7 396.90
## 6 0.02985 0.0 2.18 0 0.458 6.430 58.7 6.0622 3 222 18.7 394.12
## 7 0.08829 12.5 7.87 0 0.524 6.012 66.6 5.5605 5 311 15.2 395.60
## 8 0.14455 12.5 7.87 0 0.524 6.172 96.1 5.9505 5 311 15.2 396.90
## 9 0.21124 12.5 7.87 0 0.524 5.631 100.0 6.0821 5 311 15.2 386.63
## 10 0.17004 12.5 7.87 0 0.524 6.004 85.9 6.5921 5 311 15.2 386.71
## 11 0.22489 12.5 7.87 0 0.524 6.377 94.3 6.3467 5 311 15.2 392.52
## 12 0.11747 12.5 7.87 0 0.524 6.009 82.9 6.2267 5 311 15.2 396.90
## 13 0.09378 12.5 7.87 0 0.524 5.889 39.0 5.4509 5 311 15.2 390.50
## 14 0.62976 0.0 8.14 0 0.538 5.949 61.8 4.7075 4 307 21.0 396.90
## 15 0.63796 0.0 8.14 0 0.538 6.096 84.5 4.4619 4 307 21.0 380.02
## lstat medv
## 1 4.98 24.0
## 2 9.14 21.6
## 3 4.03 34.7
## 4 2.94 33.4
## 5 5.33 36.2
## 6 5.21 28.7
## 7 12.43 22.9
## 8 19.15 27.1
## 9 29.93 16.5
## 10 17.10 18.9
## 11 20.45 15.0
## 12 13.27 18.9
## 13 15.71 21.7
## 14 8.26 20.4
## 15 10.26 18.2
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
The Boston dataset is aiming to see the housing values in suburbs of Boston which includes 14 variables and 506 rows and it contains the following columns:
- crim: per capita crime rate by town.
- zn: proportion of residential land zoned for lots over 25,000 sq.ft.
- indus: proportion of non-retail business acres per town.
- chas: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise).
- nox: nitrogen oxides concentration (parts per 10 million).
- rm: average number of rooms per dwelling.
- age: proportion of owner-occupied units built prior to 1940.
- dis: weighted mean of distances to five Boston employment centres.
- rad: index of accessibility to radial highways.
- tax: full-value property-tax rate per $10,000.
- ptratio: pupil-teacher ratio by town.
- black: 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town.
- lstat: lower status of the population (percent).
- medv: median value of owner-occupied homes in $1000s.
Check the correlations between variables via correlation matrix plot.
## corrplot 0.84 loaded
If the relationship between two variables are more related, the circle would be more bigger and darker. According to the size and color of the circles, we can observe that those variables are related as following:
- crim: rad, tax
- zn: dis, age, indus
- indus: nox, dis, tax
- chas: N/A
- nox: age, dis, tax
- rm: latat, medv
- age: dis, lstat
- dis: rad, tax, lstat
- rad: tax
- tax: lstat
- ptratio: medv
- black: crim, rad, tax…
- lstat: rm, age…
- medv: rm
Summary Boston dataset
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
## crim zn indus chas nox rm age
## 1 -0.4193669 0.2845483 -1.2866362 -0.2723291 -0.1440749 0.4132629 -0.1198948
## 2 -0.4169267 -0.4872402 -0.5927944 -0.2723291 -0.7395304 0.1940824 0.3668034
## 3 -0.4169290 -0.4872402 -0.5927944 -0.2723291 -0.7395304 1.2814456 -0.2655490
## 4 -0.4163384 -0.4872402 -1.3055857 -0.2723291 -0.8344581 1.0152978 -0.8090878
## 5 -0.4120741 -0.4872402 -1.3055857 -0.2723291 -0.8344581 1.2273620 -0.5106743
## 6 -0.4166314 -0.4872402 -1.3055857 -0.2723291 -0.8344581 0.2068916 -0.3508100
## dis rad tax ptratio black lstat medv
## 1 0.140075 -0.9818712 -0.6659492 -1.4575580 0.4406159 -1.0744990 0.1595278
## 2 0.556609 -0.8670245 -0.9863534 -0.3027945 0.4406159 -0.4919525 -0.1014239
## 3 0.556609 -0.8670245 -0.9863534 -0.3027945 0.3960351 -1.2075324 1.3229375
## 4 1.076671 -0.7521778 -1.1050216 0.1129203 0.4157514 -1.3601708 1.1815886
## 5 1.076671 -0.7521778 -1.1050216 0.1129203 0.4406159 -1.0254866 1.4860323
## 6 1.076671 -0.7521778 -1.1050216 0.1129203 0.4101651 -1.0422909 0.6705582
## crim zn indus chas
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563 Min. :-0.2723
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668 1st Qu.:-0.2723
## Median :-0.390280 Median :-0.48724 Median :-0.2109 Median :-0.2723
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150 3rd Qu.:-0.2723
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202 Max. : 3.6648
## nox rm age dis
## Min. :-1.4644 Min. :-3.8764 Min. :-2.3331 Min. :-1.2658
## 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366 1st Qu.:-0.8049
## Median :-0.1441 Median :-0.1084 Median : 0.3171 Median :-0.2790
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059 3rd Qu.: 0.6617
## Max. : 2.7296 Max. : 3.5515 Max. : 1.1164 Max. : 3.9566
## rad tax ptratio black
## Min. :-0.9819 Min. :-1.3127 Min. :-2.7047 Min. :-3.9033
## 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876 1st Qu.: 0.2049
## Median :-0.5225 Median :-0.4642 Median : 0.2746 Median : 0.3808
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058 3rd Qu.: 0.4332
## Max. : 1.6596 Max. : 1.7964 Max. : 1.6372 Max. : 0.4406
## lstat medv
## Min. :-1.5296 Min. :-1.9063
## 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 3.5453 Max. : 2.9865
p.s. Use the quantiles as the break points in the categorical variable
# class of the boston_scaled object
class(Boston_scale)
## [1] "matrix"
Boston_scale <- as.data.frame(Boston_scale)
# create a quantile vector of crim and print it
bins <- quantile(Boston_scale$crim)
bins
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
# create a categorical variable 'crime'
crime <- cut(Boston_scale$crim, breaks = bins, include.lowest = TRUE)
table(crime)
## crime
## [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
## 127 126 126 127
# remove original crim from the dataset
Boston_scale <- dplyr::select(Boston_scale, -crim)
# add the new categorical value to scaled data
Boston_scale <- data.frame(Boston_scale, crime)
# number of rows in the Boston dataset
n <- nrow(Boston_scale)
# choose randomly 80% of the rows
ind <- sample(n, size = n * 0.8)
# create train set
train <- Boston_scale[ind,]
# create test set
test <- Boston_scale[-ind,]
# save the correct classes from test data
correct_classes <- Boston_scale[-ind,]$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime)
# linear discriminant analysis
lda.fit <- lda(crime~., data = train)
# print the lda.fit object
lda.fit
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
## 0.2252475 0.2673267 0.2549505 0.2524752
##
## Group means:
## zn indus chas nox rm
## [-0.419,-0.411] 0.9484371 -0.8747457 -0.09926972 -0.8510538 0.36932985
## (-0.411,-0.39] -0.1269531 -0.3274074 0.01930799 -0.5718088 -0.15312477
## (-0.39,0.00739] -0.3939928 0.2498552 0.22458650 0.4386454 -0.02449016
## (0.00739,9.92] -0.4872402 1.0171096 -0.04073494 1.0550429 -0.35466429
## age dis rad tax ptratio
## [-0.419,-0.411] -0.8843939 0.8688991 -0.6751926 -0.7269133 -0.359644394
## (-0.411,-0.39] -0.3233765 0.3604388 -0.5533229 -0.4861339 0.009419327
## (-0.39,0.00739] 0.3958101 -0.3824769 -0.4054077 -0.2856924 -0.341809809
## (0.00739,9.92] 0.8143192 -0.8521663 1.6382099 1.5141140 0.780871766
## black lstat medv
## [-0.419,-0.411] 0.3804281 -0.74164606 0.47735358
## (-0.411,-0.39] 0.3163837 -0.13517395 -0.02480962
## (-0.39,0.00739] 0.0815872 0.07293317 0.10442391
## (0.00739,9.92] -0.8093921 0.86102093 -0.66607309
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.08679235 0.781159419 -0.94437495
## indus 0.02673867 -0.294653205 0.02009446
## chas -0.02349640 -0.032072092 0.11247027
## nox 0.38802612 -0.616558047 -1.23720672
## rm 0.06581356 -0.026356166 -0.10649588
## age 0.24571796 -0.332049583 -0.01788384
## dis -0.10628569 -0.298844927 0.20633818
## rad 3.23725839 0.842032505 -0.18079362
## tax -0.05516616 0.007653876 0.69037386
## ptratio 0.13677546 0.071656198 -0.08268479
## black -0.10209395 0.005152997 0.08692786
## lstat 0.21516333 -0.240710647 0.32115089
## medv 0.10039084 -0.410453925 -0.20609159
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9501 0.0372 0.0127
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime)
# plot the lda results
plot(lda.fit, dimen = 2)
lda.arrows(lda.fit, myscale = 1)
# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)
# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
## [-0.419,-0.411] 22 13 1 0
## (-0.411,-0.39] 6 9 3 0
## (-0.39,0.00739] 0 10 12 1
## (0.00739,9.92] 0 0 0 25
library(MASS)
data('Boston')
# scale the dataset
bs <- scale(Boston)
bs <- as.data.frame(bs)
# distance measure 1: euclidean distance matrix
dist_eu <- dist(bs, method = "euclidean")
# look at the summary of the distances
summary(dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.4625 4.8241 4.9111 6.1863 14.3970
# distance measure 2: manhattan distance matrix
dist_man <- dist(bs, method = "manhattan")
# look at the summary of the distances
summary(dist_man)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.2662 8.4832 12.6090 13.5488 17.7568 48.8618
# k-means clustering
# plot the Boston dataset with clusters
km <-kmeans(bs, centers = 4)
pairs(bs[6:10], col = km$cluster)
# k-means clustering
km <-kmeans(bs, centers = 3)
pairs(bs[6:10], col = km$cluster)
# k-means clustering
km <-kmeans(bs, centers = 2)
pairs(bs[6:10], col = km$cluster)
# k-means clustering
km <-kmeans(bs, centers = 1)
pairs(bs[6:10], col = km$cluster)
As shown in the k-means graph above (from center=4 to 1), the pair graph with center=2 seems the most resonable seperation. In the graph when center=3, some cluster are ambiguous winthin one group.
Boston_scale_original <- scale(Boston)
Boston_scale_original <- as.data.frame(Boston_scale_original)
# k-means clustering
km_original <-kmeans(Boston_scale_original, centers = 4)
pairs(Boston_scale_original[6:10], col = km_original$cluster)
# k-means clustering
km_original <-kmeans(Boston_scale_original, centers = 3)
pairs(Boston_scale_original[6:10], col = km_original$cluster)
Interpret the results. Which variables are the most influencial linear separators for the clusters? (0-2 points to compensate any loss of points from the above exercises)
Run the code below for the (scaled) train data that you used to fit the LDA. The code creates a matrix product, which is a projection of the data points.
(0-3 points) Describe and interpret the outputs, commenting on the distributions of the variables and the relationships between them.
human_ <- read.csv(file = "data/human.csv", sep = ",", header = TRUE)
# Access GGally
library(GGally)
# visualize the 'human_' variables
ggpairs(human_,
title="human data", # title of the plot
colour = "sex") # aesthetics, ggplot2 style
## Warning in warn_if_args_exist(list(...)): Extra arguments: 'colour' are being
## ignored. If these are meant to be aesthetics, submit them using the 'mapping'
## variable within ggpairs with ggplot2::aes or ggplot2::aes_string.
# compute the correlation matrix and visualize it with corrplot
cor(human_)
## Edu2.FM Labo.FM Life.Exp Edu.Exp GNI
## Edu2.FM 1.000000000 0.009564039 0.5760299 0.59325156 0.43030485
## Labo.FM 0.009564039 1.000000000 -0.1400125 0.04732183 -0.02173971
## Life.Exp 0.576029853 -0.140012504 1.0000000 0.78943917 0.62666411
## Edu.Exp 0.593251562 0.047321827 0.7894392 1.00000000 0.62433940
## GNI 0.430304846 -0.021739705 0.6266641 0.62433940 1.00000000
## Mat.Mor -0.660931770 0.240461075 -0.8571684 -0.73570257 -0.49516234
## Ado.Birth -0.529418415 0.120158862 -0.7291774 -0.70356489 -0.55656208
## Parli.F 0.078635285 0.250232608 0.1700863 0.20608156 0.08920818
## Mat.Mor Ado.Birth Parli.F
## Edu2.FM -0.6609318 -0.5294184 0.07863528
## Labo.FM 0.2404611 0.1201589 0.25023261
## Life.Exp -0.8571684 -0.7291774 0.17008631
## Edu.Exp -0.7357026 -0.7035649 0.20608156
## GNI -0.4951623 -0.5565621 0.08920818
## Mat.Mor 1.0000000 0.7586615 -0.08944000
## Ado.Birth 0.7586615 1.0000000 -0.07087810
## Parli.F -0.0894400 -0.0708781 1.00000000
This Human dataset contains the information about Human Development Index (HDI) which includes Edu2.FM (Female education index), Labo.FM (Female labour market index), Life.Exp (Life expectancy index), Edu.Exp (Education epectancy index), GNI (Gross national income), Mat.Mor (Maternal mortality ratio), Ado.Birth (Adolescent birth rate) and Parli.F (Female shares of parliamentary seats) as the dataset variables.
HDI has three dimentions, including Long and healthy life, Knowledge and A decent standard of living which are able to be evaluated by life expentanct index, education index and GNI index.
According to the human data distribution plot, we can see the correlation between Life.Exp, Edu.Exp and GNI are highly related (> 0.6)
(0-2 points) - Perform PCA on the not standardized human data. Show the variability captured by the principal components. - Draw a biplot displaying the observations by the first two principal components (PC1 coordinate in x-axis, PC2 coordinate in y-axis), along with arrows representing the original variables.
# perform principal component analysis on the not standardized human data
pca_human <- prcomp(human_)
pca_human
## Standard deviations (1, .., p=8):
## [1] 1.854416e+04 1.855219e+02 2.518701e+01 1.145441e+01 3.766241e+00
## [6] 1.565912e+00 1.912052e-01 1.591112e-01
##
## Rotation (n x k) = (8 x 8):
## PC1 PC2 PC3 PC4 PC5
## Edu2.FM -5.607472e-06 0.0006713951 -3.412027e-05 -2.736326e-04 -0.0022935252
## Labo.FM 2.331945e-07 -0.0002819357 5.302884e-04 -4.692578e-03 0.0022190154
## Life.Exp -2.815823e-04 0.0283150248 1.294971e-02 -6.752684e-02 0.9865644425
## Edu.Exp -9.562910e-05 0.0075529759 1.427664e-02 -3.313505e-02 0.1431180282
## GNI -9.999832e-01 -0.0057723054 -5.156742e-04 4.932889e-05 -0.0001135863
## Mat.Mor 5.655734e-03 -0.9916320120 1.260302e-01 -6.100534e-03 0.0266373214
## Ado.Birth 1.233961e-03 -0.1255502723 -9.918113e-01 5.301595e-03 0.0188618600
## Parli.F -5.526460e-05 0.0032317269 -7.398331e-03 -9.971232e-01 -0.0716401914
## PC6 PC7 PC8
## Edu2.FM 2.180183e-02 6.998623e-01 7.139410e-01
## Labo.FM 3.264423e-02 7.132267e-01 -7.001533e-01
## Life.Exp -1.453515e-01 5.380452e-03 2.281723e-03
## Edu.Exp 9.882477e-01 -3.826887e-02 7.776451e-03
## GNI -2.711698e-05 -8.075191e-07 -1.176762e-06
## Mat.Mor 1.695203e-03 1.355518e-04 8.371934e-04
## Ado.Birth 1.273198e-02 -8.641234e-05 -1.707885e-04
## Parli.F -2.309896e-02 -2.642548e-03 2.680113e-03
# draw a biplot of the principal component representation and the original variables
biplot(pca_human, choices = 1:2)
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
According to the biplot, the GNI tends to PC2 dimension and others variables tend to PC1 dimension.
(0-4 points) - Standardize the variables in the human data and repeat the above analysis. Interpret the results of both analysis (with and without standardizing). - Are the results different? Why or why not? Include captions (brief descriptions) in your plots where you describe the results by using not just your variable names, but the actual phenomenons they relate to.
# standardize the variables
human_std <- scale(human_)
# print out summaries of the standardized variables
summary(human_std)
## Edu2.FM Labo.FM Life.Exp Edu.Exp
## Min. :-2.8189 Min. :-2.6247 Min. :-2.7188 Min. :-2.7378
## 1st Qu.:-0.5233 1st Qu.:-0.5484 1st Qu.:-0.6425 1st Qu.:-0.6782
## Median : 0.3503 Median : 0.2316 Median : 0.3056 Median : 0.1140
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.5958 3rd Qu.: 0.7350 3rd Qu.: 0.6717 3rd Qu.: 0.7126
## Max. : 2.6646 Max. : 1.6632 Max. : 1.4218 Max. : 2.4730
## GNI Mat.Mor Ado.Birth Parli.F
## Min. :-0.9193 Min. :-0.6992 Min. :-1.1325 Min. :-1.8203
## 1st Qu.:-0.7243 1st Qu.:-0.6496 1st Qu.:-0.8394 1st Qu.:-0.7409
## Median :-0.3013 Median :-0.4726 Median :-0.3298 Median :-0.1403
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.3712 3rd Qu.: 0.1932 3rd Qu.: 0.6030 3rd Qu.: 0.6127
## Max. : 5.6890 Max. : 4.4899 Max. : 3.8344 Max. : 3.1850
# perform principal component analysis (with the SVD method)
pca_human_std <- prcomp(human_std)
# draw a biplot of the principal component representation and the original variables
biplot(pca_human_std, choices = 1:2)
According to the biplot with standardized data, the Edu2.FM (Female education index), Life.Exp (Life expectancy index), Edu.Exp (Education epectancy index) and GNI (Gross national income) are related and tend to PC2 dimension. Comparing to the non-standardized data, the biplot with standardized data is more clearer to interpret the correlation between the several variables.
(0-2 points) Give your personal interpretations of the first two principal component dimensions based on the biplot drawn after PCA on the standardized human data.
After the dimension reduction by PCA, we can see the better cluster in biplot. In the first plot, we can only see the dimension tendency of index GNI is different from others. However, in the second plot, we see the indeies are devided into three parts.
(0-4 points) - Load the tea dataset from the package Factominer. Explore the data briefly: look at the structure and the dimensions of the data and visualize it. - Do Multiple Correspondence Analysis on the tea data (or to a certain columns of the data, it’s up to you). - Interpret the results of the MCA and draw at least the variable biplot of the analysis. You can also explore other plotting options for MCA. Comment on the output of the plots.
# load packages
require(FactoMineR)
## Loading required package: FactoMineR
require(ggplot2)
require(dplyr)
require(tidyr)
## Loading required package: tidyr
##
## Attaching package: 'tidyr'
## The following object is masked from 'package:magrittr':
##
## extract
library("FactoMineR")
# load data tea
data(tea)
# column names to keep in the dataset
#keep_columns <- c("Tea", "How", "how", "sugar", "where", "lunch")
# select the 'keep_columns' to create a new dataset
tea_time <- tea[, c(13, 14, 16, 15, 4, 17)]
# look at the summaries and structure of the data
summary(tea_time)
## Tea How how sugar
## black : 74 alone:195 tea bag :170 No.sugar:155
## Earl Grey:193 lemon: 33 tea bag+unpackaged: 94 sugar :145
## green : 33 milk : 63 unpackaged : 36
## other: 9
## lunch where
## lunch : 44 chain store :192
## Not.lunch:256 chain store+tea shop: 78
## tea shop : 30
##
str(tea_time)
## 'data.frame': 300 obs. of 6 variables:
## $ Tea : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
## $ How : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
## $ how : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ sugar: Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
## $ lunch: Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
## $ where: Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
#visualize the tea data
gather(tea_time) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
## Warning: attributes are not identical across measure variables;
## they will be dropped
# multiple correspondence analysis
mca <- MCA(tea_time, graph = FALSE)
# summary of the model
summary(mca)
##
## Call:
## MCA(X = tea_time, graph = FALSE)
##
##
## Eigenvalues
## Dim.1 Dim.2 Dim.3 Dim.4 Dim.5 Dim.6 Dim.7
## Variance 0.279 0.261 0.219 0.189 0.177 0.156 0.144
## % of var. 15.238 14.232 11.964 10.333 9.667 8.519 7.841
## Cumulative % of var. 15.238 29.471 41.435 51.768 61.434 69.953 77.794
## Dim.8 Dim.9 Dim.10 Dim.11
## Variance 0.141 0.117 0.087 0.062
## % of var. 7.705 6.392 4.724 3.385
## Cumulative % of var. 85.500 91.891 96.615 100.000
##
## Individuals (the 10 first)
## Dim.1 ctr cos2 Dim.2 ctr cos2 Dim.3
## 1 | -0.298 0.106 0.086 | -0.328 0.137 0.105 | -0.327
## 2 | -0.237 0.067 0.036 | -0.136 0.024 0.012 | -0.695
## 3 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 4 | -0.530 0.335 0.460 | -0.318 0.129 0.166 | 0.211
## 5 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 6 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 7 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 8 | -0.237 0.067 0.036 | -0.136 0.024 0.012 | -0.695
## 9 | 0.143 0.024 0.012 | 0.871 0.969 0.435 | -0.067
## 10 | 0.476 0.271 0.140 | 0.687 0.604 0.291 | -0.650
## ctr cos2
## 1 0.163 0.104 |
## 2 0.735 0.314 |
## 3 0.062 0.069 |
## 4 0.068 0.073 |
## 5 0.062 0.069 |
## 6 0.062 0.069 |
## 7 0.062 0.069 |
## 8 0.735 0.314 |
## 9 0.007 0.003 |
## 10 0.643 0.261 |
##
## Categories (the 10 first)
## Dim.1 ctr cos2 v.test Dim.2 ctr cos2
## black | 0.473 3.288 0.073 4.677 | 0.094 0.139 0.003
## Earl Grey | -0.264 2.680 0.126 -6.137 | 0.123 0.626 0.027
## green | 0.486 1.547 0.029 2.952 | -0.933 6.111 0.107
## alone | -0.018 0.012 0.001 -0.418 | -0.262 2.841 0.127
## lemon | 0.669 2.938 0.055 4.068 | 0.531 1.979 0.035
## milk | -0.337 1.420 0.030 -3.002 | 0.272 0.990 0.020
## other | 0.288 0.148 0.003 0.876 | 1.820 6.347 0.102
## tea bag | -0.608 12.499 0.483 -12.023 | -0.351 4.459 0.161
## tea bag+unpackaged | 0.350 2.289 0.056 4.088 | 1.024 20.968 0.478
## unpackaged | 1.958 27.432 0.523 12.499 | -1.015 7.898 0.141
## v.test Dim.3 ctr cos2 v.test
## black 0.929 | -1.081 21.888 0.382 -10.692 |
## Earl Grey 2.867 | 0.433 9.160 0.338 10.053 |
## green -5.669 | -0.108 0.098 0.001 -0.659 |
## alone -6.164 | -0.113 0.627 0.024 -2.655 |
## lemon 3.226 | 1.329 14.771 0.218 8.081 |
## milk 2.422 | 0.013 0.003 0.000 0.116 |
## other 5.534 | -2.524 14.526 0.197 -7.676 |
## tea bag -6.941 | -0.065 0.183 0.006 -1.287 |
## tea bag+unpackaged 11.956 | 0.019 0.009 0.000 0.226 |
## unpackaged -6.482 | 0.257 0.602 0.009 1.640 |
##
## Categorical variables (eta2)
## Dim.1 Dim.2 Dim.3
## Tea | 0.126 0.108 0.410 |
## How | 0.076 0.190 0.394 |
## how | 0.708 0.522 0.010 |
## sugar | 0.065 0.001 0.336 |
## lunch | 0.000 0.064 0.111 |
## where | 0.702 0.681 0.055 |
# visualize MCA, try 4 different arguments
plot(mca)
plot(mca, invisible=c("ind"))
plot(mca, habillage = "quali")
plot(mca, invisible=c("ind"), habillage = "quali")
# variable biplot
plot(mca, axes = c(1,2), choix=c("var"))
According to the biplot above, we can see “How”, “Tea”, “lunch” and “suger” are highly related, and “where” and “how” are highly related. ***
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
summary(cars)
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
You can also embed plots, for example:
Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot. ***